﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SqlAntlr
{
    public class DBSchema
    {
        String dbName;
        Dictionary<String, RelationSchema> relations;
        List<SimpleForeignKey> fks;

        public DBSchema(String dbName)
        {
            this.dbName = dbName;
            this.relations = new Dictionary<String, RelationSchema>();
            this.fks = new List<SimpleForeignKey>();
        }

        public void setDBName(String dbName)
        {
            this.dbName = dbName;
        }

        public void AddView(String n, RelationSchema r)
        {
            Add(new RelationSchema(n, r));
        }

        public void Add(RelationSchema r)
        {
            relations[r.getRelationName()] = r;
        }

        public void addRelation(RelationSchema relation)
        {
            relations[relation.getRelationName()] = relation;
        }

        public void addForeignKey(String rel1, String col1, String rel2, String col2)
        {
            fks.Add(new SimpleForeignKey(rel1, col1, rel2, col2));
        }


        public String getDBName()
        {
            return dbName;
        }

        public RelationSchema get(String n)
        {
            return relations[n.ToLower()];
        }

        public List<RelationSchema> getRelations()
        {
            return new List<RelationSchema>(relations.Values);
        }

        public List<SimpleForeignKey> getForeignKeys()
        {
            return fks;
        }

        public class SimpleForeignKey
        {
            public String rel1;
            public String rel2;
            public String col1;
            public String col2;

            public SimpleForeignKey(String rel1, String col1, String rel2, String col2)
            {
                this.rel1 = rel1;
                this.col1 = col1;
                this.rel2 = rel2;
                this.col2 = col2;
            }

            public override bool Equals(Object other)
            {
                if (other is SimpleForeignKey)
                {
                    SimpleForeignKey o = (SimpleForeignKey)other;
                    return rel1.Equals(o.rel1) && rel2.Equals(o.rel2) && col1.Equals(o.col1) && col2.Equals(o.col2);
                }
                else
                {
                    return false;
                }
            }

            public String toString()
            {
                return rel1 + "." + col1 + "=" + rel2 + "." + col2;
            }

            public override int GetHashCode()
            {
                return ToString().GetHashCode();
            }

        }
    }
}
